package br.com.seosoft.simplecalcfinan.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import br.com.seosoft.simplecalcfinan.R;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements
		TimePickerDialog.OnTimeSetListener {

	private Button btnTime;
	private String timeString;
	private Date data;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current time as the default values for the picker
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);

		// Create a new instance of TimePickerDialog and return it
		btnTime = (Button) getActivity().findViewById(R.id.BtnHora);

		if (btnTime.getText().equals("Hora")) {
			// Create a new instance of DatePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					DateFormat.is24HourFormat(getActivity()));
		} else {

			timeString = btnTime.getText().toString().trim();
			SimpleDateFormat format = new SimpleDateFormat("HH:mm",
					Locale.getDefault());

			try {
				data = format.parse(timeString);

				c.setTime(data);
				hour = c.get(Calendar.HOUR_OF_DAY);
				minute = c.get(Calendar.MINUTE);

				return new TimePickerDialog(getActivity(), this, hour, minute,
						DateFormat.is24HourFormat(getActivity()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
				return new TimePickerDialog(getActivity(), this, hour, minute,
						DateFormat.is24HourFormat(getActivity()));
			}

		}

	}

	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		// Do something with the time chosen by the user

		btnTime.setText(new StringBuilder().append(hourOfDay).append(":")
				.append(minute));
	}
}